<template>
  <div class="model-management-index">
    <div class="page-header">
      <h2>模型管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
        <el-button type="success" @click="createModel">
          <el-icon><Plus /></el-icon>
          新建模型
        </el-button>
      </div>
    </div>

    <!-- 模型概览统计 -->
    <div class="overview-stats">
      <div class="stat-card">
        <div class="stat-icon models">
          <el-icon><Cpu /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.totalModels }}</div>
          <div class="stat-label">总模型数</div>
        </div>
        <div class="stat-trend">
          <span class="trend-value">+12%</span>
          <span class="trend-label">本月新增</span>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon training">
          <el-icon><DataAnalysis /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.trainingModels }}</div>
          <div class="stat-label">训练中</div>
        </div>
        <div class="stat-trend">
          <span class="trend-value">{{ statistics.trainingModels }}/{{ statistics.totalModels }}</span>
          <span class="trend-label">训练占比</span>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon deployed">
          <el-icon><CloudUpload /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.deployedModels }}</div>
          <div class="stat-label">已部署</div>
        </div>
        <div class="stat-trend">
          <span class="trend-value">{{ (statistics.deployedModels / statistics.totalModels * 100).toFixed(1) }}%</span>
          <span class="trend-label">部署率</span>
        </div>
      </div>

      <div class="stat-card">
        <div class="stat-icon performance">
          <el-icon><TrendCharts /></el-icon>
        </div>
        <div class="stat-content">
          <div class="stat-number">{{ statistics.avgAccuracy }}%</div>
          <div class="stat-label">平均准确率</div>
        </div>
        <div class="stat-trend">
          <span class="trend-value">+2.3%</span>
          <span class="trend-label">较上月提升</span>
        </div>
      </div>
    </div>

    <!-- 快速操作区 -->
    <div class="quick-actions">
      <h3>快速操作</h3>
      <div class="action-grid">
        <div class="action-card" @click="navigateTo('/admin/model-management/training-monitoring')">
          <div class="action-icon">
            <el-icon><Monitor /></el-icon>
          </div>
          <div class="action-content">
            <h4>训练监控</h4>
            <p>实时监控模型训练状态和进度</p>
          </div>
          <div class="action-badge">
            <el-badge :value="statistics.trainingModels" type="warning" />
          </div>
        </div>

        <div class="action-card" @click="navigateTo('/admin/model-management/performance-evaluation')">
          <div class="action-icon">
            <el-icon><PieChart /></el-icon>
          </div>
          <div class="action-content">
            <h4>性能评估</h4>
            <p>评估模型性能指标和效果</p>
          </div>
          <div class="action-badge">
            <el-badge :value="statistics.evaluationTasks" type="primary" />
          </div>
        </div>

        <div class="action-card" @click="navigateTo('/admin/model-management/parameter-optimization')">
          <div class="action-icon">
            <el-icon><Setting /></el-icon>
          </div>
          <div class="action-content">
            <h4>参数优化</h4>
            <p>调整和优化模型参数配置</p>
          </div>
          <div class="action-badge">
            <el-badge :value="statistics.optimizationTasks" type="success" />
          </div>
        </div>

        <div class="action-card" @click="navigateTo('/admin/model-management/dataset-management')">
          <div class="action-icon">
            <el-icon><Database /></el-icon>
          </div>
          <div class="action-content">
            <h4>数据集管理</h4>
            <p>管理训练和测试数据集</p>
          </div>
          <div class="action-badge">
            <el-badge :value="statistics.totalDatasets" type="info" />
          </div>
        </div>
      </div>
    </div>

    <!-- 最新模型动态 -->
    <div class="recent-activities">
      <h3>最新模型动态</h3>
      <div class="activity-list">
        <div class="activity-item" v-for="activity in recentActivities" :key="activity.id">
          <div class="activity-icon" :class="activity.type">
            <el-icon><component :is="getActivityIcon(activity.type)" /></el-icon>
          </div>
          <div class="activity-content">
            <div class="activity-title">{{ activity.title }}</div>
            <div class="activity-description">{{ activity.description }}</div>
            <div class="activity-time">{{ formatDate(activity.timestamp) }}</div>
          </div>
          <div class="activity-status">
            <el-tag :type="getStatusColor(activity.status)">{{ activity.status }}</el-tag>
          </div>
        </div>
      </div>
    </div>

    <!-- 模型性能图表 -->
    <div class="performance-charts">
      <div class="chart-section">
        <h3>模型性能趋势</h3>
        <div class="chart-container">
          <div ref="performanceChart" class="chart"></div>
        </div>
      </div>
      
      <div class="chart-section">
        <h3>模型类型分布</h3>
        <div class="chart-container">
          <div ref="distributionChart" class="chart"></div>
        </div>
      </div>
    </div>

    <!-- 系统资源使用情况 -->
    <div class="resource-usage">
      <h3>系统资源使用</h3>
      <div class="resource-grid">
        <div class="resource-item">
          <div class="resource-label">GPU使用率</div>
          <div class="resource-progress">
            <el-progress 
              :percentage="resourceUsage.gpu" 
              :color="getProgressColor(resourceUsage.gpu)"
              :stroke-width="8"
            />
          </div>
          <div class="resource-value">{{ resourceUsage.gpu }}%</div>
        </div>

        <div class="resource-item">
          <div class="resource-label">内存使用</div>
          <div class="resource-progress">
            <el-progress 
              :percentage="resourceUsage.memory" 
              :color="getProgressColor(resourceUsage.memory)"
              :stroke-width="8"
            />
          </div>
          <div class="resource-value">{{ resourceUsage.memory }}%</div>
        </div>

        <div class="resource-item">
          <div class="resource-label">存储空间</div>
          <div class="resource-progress">
            <el-progress 
              :percentage="resourceUsage.storage" 
              :color="getProgressColor(resourceUsage.storage)"
              :stroke-width="8"
            />
          </div>
          <div class="resource-value">{{ resourceUsage.storage }}%</div>
        </div>

        <div class="resource-item">
          <div class="resource-label">网络带宽</div>
          <div class="resource-progress">
            <el-progress 
              :percentage="resourceUsage.network" 
              :color="getProgressColor(resourceUsage.network)"
              :stroke-width="8"
            />
          </div>
          <div class="resource-value">{{ resourceUsage.network }}%</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { 
  Refresh, Plus, Cpu, DataAnalysis, CloudUpload, TrendCharts,
  Monitor, PieChart, Setting, Database, Clock, Check, Warning, Info
} from '@element-plus/icons-vue'

const router = useRouter()

// 图表实例
const performanceChart = ref(null)
const distributionChart = ref(null)
let performanceChartInstance = null
let distributionChartInstance = null

// 统计数据
const statistics = reactive({
  totalModels: 42,
  trainingModels: 3,
  deployedModels: 28,
  avgAccuracy: 94.2,
  evaluationTasks: 8,
  optimizationTasks: 5,
  totalDatasets: 156
})

// 资源使用情况
const resourceUsage = reactive({
  gpu: 73,
  memory: 68,
  storage: 45,
  network: 32
})

// 最新活动
const recentActivities = ref([
  {
    id: 1,
    type: 'training',
    title: '文本检测模型训练完成',
    description: 'TextDetection-v3.2 模型训练已完成，准确率达到95.8%',
    timestamp: '2024-01-15T14:30:00',
    status: '已完成'
  },
  {
    id: 2,
    type: 'evaluation',
    title: '图像识别模型性能评估',
    description: 'ImageRecognition-v2.1 模型正在进行性能评估测试',
    timestamp: '2024-01-15T13:45:00',
    status: '进行中'
  },
  {
    id: 3,
    type: 'optimization',
    title: '语音识别参数优化',
    description: 'VoiceRecognition-v1.5 模型参数优化任务已启动',
    timestamp: '2024-01-15T12:20:00',
    status: '进行中'
  },
  {
    id: 4,
    type: 'deployment',
    title: '模型部署成功',
    description: 'FraudDetection-v4.0 模型已成功部署到生产环境',
    timestamp: '2024-01-15T11:15:00',
    status: '已完成'
  }
])

// 方法
const navigateTo = (path) => {
  router.push(path)
}

const refreshData = () => {
  ElMessage.success('数据刷新成功')
}

const createModel = () => {
  ElMessage.info('新建模型功能开发中...')
}

const initPerformanceChart = () => {
  if (!performanceChart.value) return

  performanceChartInstance = echarts.init(performanceChart.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross'
      }
    },
    legend: {
      data: ['准确率', '召回率', 'F1分数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月']
    },
    yAxis: {
      type: 'value',
      min: 85,
      max: 100,
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [
      {
        name: '准确率',
        type: 'line',
        data: [89.2, 91.5, 93.1, 94.8, 94.2, 95.1, 94.8],
        smooth: true,
        itemStyle: { color: '#409EFF' }
      },
      {
        name: '召回率',
        type: 'line',
        data: [87.8, 89.3, 91.2, 92.5, 93.8, 94.2, 93.9],
        smooth: true,
        itemStyle: { color: '#67C23A' }
      },
      {
        name: 'F1分数',
        type: 'line',
        data: [88.5, 90.4, 92.1, 93.6, 94.0, 94.6, 94.3],
        smooth: true,
        itemStyle: { color: '#E6A23C' }
      }
    ]
  }

  performanceChartInstance.setOption(option)
}

const initDistributionChart = () => {
  if (!distributionChart.value) return

  distributionChartInstance = echarts.init(distributionChart.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['文本检测', '图像识别', '语音识别', '视频分析', '多模态融合']
    },
    series: [
      {
        name: '模型类型',
        type: 'pie',
        radius: '55%',
        center: ['50%', '60%'],
        data: [
          { value: 12, name: '文本检测' },
          { value: 15, name: '图像识别' },
          { value: 8, name: '语音识别' },
          { value: 5, name: '视频分析' },
          { value: 2, name: '多模态融合' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }

  distributionChartInstance.setOption(option)
}

const getActivityIcon = (type) => {
  const icons = {
    training: DataAnalysis,
    evaluation: PieChart,
    optimization: Setting,
    deployment: CloudUpload
  }
  return icons[type] || Info
}

const getStatusColor = (status) => {
  const colors = {
    '已完成': 'success',
    '进行中': 'warning',
    '等待中': 'info',
    '失败': 'danger'
  }
  return colors[status] || 'info'
}

const getProgressColor = (percentage) => {
  if (percentage >= 80) return '#f56c6c'
  if (percentage >= 60) return '#e6a23c'
  return '#67c23a'
}

const formatDate = (date) => {
  return new Date(date).toLocaleString('zh-CN')
}

const handleResize = () => {
  if (performanceChartInstance) {
    performanceChartInstance.resize()
  }
  if (distributionChartInstance) {
    distributionChartInstance.resize()
  }
}

// 生命周期
onMounted(() => {
  setTimeout(() => {
    initPerformanceChart()
    initDistributionChart()
  }, 100)
  
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (performanceChartInstance) {
    performanceChartInstance.dispose()
  }
  if (distributionChartInstance) {
    distributionChartInstance.dispose()
  }
})
</script>

<style scoped>
.model-management-index {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.overview-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 15px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
}

.stat-icon.models {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.training {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.deployed {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.performance {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.stat-trend {
  text-align: right;
}

.trend-value {
  font-size: 14px;
  font-weight: bold;
  color: #67c23a;
}

.trend-label {
  display: block;
  font-size: 12px;
  color: #999;
  margin-top: 2px;
}

.quick-actions {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.quick-actions h3 {
  margin: 0 0 20px 0;
  color: #333;
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.action-card {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.action-card:hover {
  border-color: #409eff;
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.2);
  transform: translateY(-2px);
}

.action-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f0f9ff;
  color: #409eff;
  font-size: 20px;
}

.action-content {
  flex: 1;
}

.action-content h4 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 16px;
}

.action-content p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.action-badge {
  position: absolute;
  top: -5px;
  right: -5px;
}

.recent-activities {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.recent-activities h3 {
  margin: 0 0 20px 0;
  color: #333;
}

.activity-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.activity-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background: #fafafa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.activity-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
}

.activity-icon.training {
  background: #f093fb;
}

.activity-icon.evaluation {
  background: #4facfe;
}

.activity-icon.optimization {
  background: #43e97b;
}

.activity-icon.deployment {
  background: #667eea;
}

.activity-content {
  flex: 1;
}

.activity-title {
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.activity-description {
  color: #666;
  font-size: 14px;
  margin-bottom: 5px;
}

.activity-time {
  color: #999;
  font-size: 12px;
}

.performance-charts {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 20px;
  margin-bottom: 30px;
}

.chart-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.chart-section h3 {
  margin: 0 0 20px 0;
  color: #333;
}

.chart-container {
  height: 300px;
}

.chart {
  width: 100%;
  height: 100%;
}

.resource-usage {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.resource-usage h3 {
  margin: 0 0 20px 0;
  color: #333;
}

.resource-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.resource-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background: #fafafa;
  border-radius: 8px;
}

.resource-label {
  width: 80px;
  color: #666;
  font-weight: bold;
}

.resource-progress {
  flex: 1;
}

.resource-value {
  width: 50px;
  text-align: right;
  font-weight: bold;
  color: #333;
}

@media (max-width: 1200px) {
  .performance-charts {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .model-management-index {
    padding: 10px;
  }
  
  .overview-stats {
    grid-template-columns: 1fr;
  }
  
  .action-grid {
    grid-template-columns: 1fr;
  }
  
  .resource-grid {
    grid-template-columns: 1fr;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: center;
  }
}
</style> 